package cn.conac.rc.gateway.modules.ofs.rest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.netflix.discovery.converters.Auto;

import cn.conac.rc.framework.utils.Collections3;
import cn.conac.rc.framework.utils.FastJsonUtil;
import cn.conac.rc.framework.utils.IpUtils;
import cn.conac.rc.framework.utils.MD5Utils;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.gateway.base.ResultPojo;
import cn.conac.rc.gateway.common.service.AreaService;
import cn.conac.rc.gateway.common.service.DictionaryService;
import cn.conac.rc.gateway.common.vo.AreaVo;
import cn.conac.rc.gateway.common.vo.Dictionary;
import cn.conac.rc.gateway.modules.ofs.entity.OrganizationEntity;
import cn.conac.rc.gateway.modules.ofs.service.FileService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.modules.ofs.vo.OrganizationVo;
import cn.conac.rc.gateway.modules.user.entity.OuserEntity;
import cn.conac.rc.gateway.modules.user.entity.RcUserEntity;
import cn.conac.rc.gateway.modules.user.entity.RoleEntity;
import cn.conac.rc.gateway.modules.user.entity.UserAreaEntity;
import cn.conac.rc.gateway.modules.user.entity.UserEntity;
import cn.conac.rc.gateway.modules.user.entity.UserExtEntity;
import cn.conac.rc.gateway.modules.user.service.UserService;
import cn.conac.rc.gateway.modules.user.vo.RcUserVo;
import cn.conac.rc.gateway.modules.user.vo.UserInfoVo;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.Cell;
import jxl.Range;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * 文件管理（上传、下载功能等）
 *
 * @author wangmeng
 */
@RestController
@RequestMapping(value = "ofs/file/")
@Api(tags = "文件的检索、下载等功能", description = "共通")
public class FileController
{
    @Autowired
    FileService rcFileService;

    @Autowired
    UserService userService;

    @Autowired
    OrganizationService service;

    @Autowired
    DictionaryService dicService;

    @Autowired
    AreaService areaService;

    /**
     * MD5盐
     */
    @Value("${file.md5.salt}")
    private String salt;

    /**
     * 文件配置路径(系统路径)
     */
    @Value("${file.server.path}")
    private String serverPath;

    /**
     * 清单保存地址
     */
    @Value("${file.item.path}")
    private String itemPath;

    /**
     * 批文保存地址
     */
    @Value("${file.approval.path}")
    private String approvalPath;

    /**
     * 用户头像保存地址
     */
    @Value("${file.photo.path}")
    private String photoPath;

    /**
     * 文件名长度限制
     */
    @Value("${importFile.name.maxlength}")
    private int nameMaxlength;

    /**
     * 允许导入文件后缀
     */
    @Value("${importFile.allow.suffix}")
    private String allowSuffix;

    /**
     * 文件最大值限制
     */
    @Value("${importFile.max.volume}")
    private int maxVolume;

    /**
     * 导入文件支持的行数
     */
    @Value("${importFile.max.rows}")
    private int maxrows;

    /**
     * 用户导入的初始密码
     */
    @Value("${user.passwd.init}")
    private String initPasswd;

    /**
     * 用户最后一次登录初始IP
     */
    @Value("${user.last.login.ip.init}")
    private String initLastLoginIp;

    /**
     * 导入用户的最大长度
     */
    @Value("${user.fullName.maxLength}")
    private int fullNameMaxLen;

    /**
     * 导入所属科室的最大长度
     */
    @Value("${user.deptName.maxLength}")
    private int deptNameMaxLen;

    @ApiOperation(value = "文件信息存储", httpMethod = "POST", response = JSONObject.class, notes = "文件信息存储")
    @RequestMapping(value = "saveFile", method = RequestMethod.POST)
    public JSONObject cudSaveFile(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "appFile对象", required = true) @RequestBody JSONObject ofsAppFiles)
    {
        return rcFileService.saveFile(ofsAppFiles);
    }

    @ApiOperation(value = "文件下载", httpMethod = "GET", response = JSONObject.class, notes = "文件下载")
    @RequestMapping(value = "download/{fileId}", method = RequestMethod.GET)
    public JSONObject cudDownload(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("fileId") @ApiParam(value = "文件ID", required = true) String fileId)
    {
        return rcFileService.download(fileId);
    }

    @ApiOperation(value = "文件检索", httpMethod = "GET", response = JSONObject.class, notes = "文件检索")
    @RequestMapping(value = "search/{fileId}", method = RequestMethod.GET)
    public JSONObject searchFile(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("fileId") @ApiParam(value = "文件ID", required = true) String fileId)
    {
        return rcFileService.searchFile(fileId);
    }

    @ApiOperation(value = "文件删除(逻辑删除)", httpMethod = "POST", response = JSONObject.class, notes = "文件删除(逻辑删除)")
    @RequestMapping(value = "deleteInLogic", method = RequestMethod.POST)
    public JSONObject cudUpdateDuty(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("fileId") @ApiParam(value = "文件ID", required = true) String fileId)
    {
        return rcFileService.deleteFileInlogic(fileId);
    }

    @ApiOperation(value = "文件删除(物理删除)", httpMethod = "POST", response = JSONObject.class, notes = "文件删除(物理删除)")
    @RequestMapping(value = "deleteInPhysics", method = RequestMethod.POST)
    public JSONObject cudDeleteFileInPhysics(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("fileId") @ApiParam(value = "文件ID", required = true) String fileId)
            throws RestClientException, Exception
    {
        return rcFileService.deleteFileInPhysics(fileId);
    }

    @ApiOperation(value = "文件上传", httpMethod = "POST", response = JSONObject.class, notes = "文件上传")
    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public ResultPojo cudUploadFile(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "文件对象", required = true) @RequestBody MultipartFile file)
    {

        // 返回结果result定义
        ResultPojo result = new ResultPojo();

        // 上传文件的校验
        String msg = this.checkFileProperties(file, 0, 0, null);
        if (StringUtils.isNotBlank(msg)) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg(msg);
            return result;
        }

        // 获取文件名称
        String fileName = file.getOriginalFilename();

        // 获取文件相对路径
        String relativePath = StringUtils.EMPTY;
        StringBuffer rPath = new StringBuffer(relativePath);
        relativePath = rPath.append(this.relativePathCreator(fileName)).toString();

        // 绝对路径生成
        StringBuffer absolutePath = new StringBuffer(serverPath);
        String fullPath = absolutePath.append(relativePath).toString();

        // 调用文件存储
        File dest = new File(fullPath);
        try {
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
        } catch (IOException e) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg("上传文件到目标地址失败！");
            return result;
        }

        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setMsg("文件上传成功！");
        result.setResult(fullPath);

        return result;
    }

    /**
     * 通过当前时间的MD5值计算文件的服务器相对路径
     *
     * @return 相对路径
     */
    private String relativePathCreator(String fileName)
    {
        String relativePath = StringUtils.EMPTY;
        MD5Utils encoderMd5 = new MD5Utils(salt, "MD5");
        String encode = encoderMd5.encode(Long.toString(new Date().getTime()));
        StringBuilder sb = new StringBuilder(encode.substring(0, 4));
        relativePath = sb.append("/").append(encode.substring(4, 8))
                .append("/").append(encode.substring(8, 12))
                .append("/").append(encode.substring(12, 16))
                .append("/").append(encode.substring(16, 31))
                .append("/").append(fileName).toString();

        return relativePath.toLowerCase(Locale.ENGLISH);
    }

    @ApiOperation(value = "部门库文件导入", httpMethod = "POST", response = JSONObject.class, notes = "部门库文件导入")
    @RequestMapping(value = "import/{areaid}", method = RequestMethod.POST)
    public Object cudImportOrganizationByExcel(HttpServletRequest request, HttpServletResponse response,@ApiParam(value = "地区id", required = true) @PathVariable String areaid,
            @ApiParam(value = "导入文件对象", required = true) @RequestBody MultipartFile file)
    {

        // 返回结果result定义
        ResultPojo resultInfo = new ResultPojo();

        //参数1，地区id
        //参数2，导入方式 0-全部 1-用户 2-部门库
        //地区id
//        areaid = "C1F11D57F2DDF60DE04011ACAA466B27";
        if (StringUtils.isBlank(areaid)) {
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("【地区id】为空");
            return resultInfo;
        }

//		if(StringUtils.isBlank(UserUtils.getCurrentUser().getOrgId())) {
//			resultInfo.setCode(ResultPojo.CODE_FAILURE);
//			resultInfo.setMsg("未绑定部门库错误");
//			resultInfo.setResult("当前用户没有绑定部门库，不能进行导入账号操作，请先为该用户绑定部门库");
//			return resultInfo;
//		}
        // 上传文件的校验
        String msg = this.checkFileProperties(file, 0, 0, null);
        if (StringUtils.isNotBlank(msg)) {
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg(msg);
            return resultInfo;
        }

        List<UserInfoVo> userInfoVoList = new ArrayList<UserInfoVo>();
        List<OrganizationEntity> orgEntityList = new ArrayList<OrganizationEntity>();
        // 将文件内容封装成UserInfoVo的list并检查输入对数据是否满足指定要求
        InputStream inputStreamFile = null;
        Workbook wb = null;

        try {
            inputStreamFile = file.getInputStream();
            wb = Workbook.getWorkbook(inputStreamFile);
        } catch (BiffException e) {
            //e.printStackTrace();
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("文件格式错误");
            resultInfo.setResult("导入只支持EXCEL 97-2003版本");
            return resultInfo;
        } catch (IOException e) {
            //e.printStackTrace();
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("文件读取错误：" + e.getMessage());
            resultInfo.setResult(null);
            return resultInfo;
        }
        Sheet sheet = wb.getSheet(0);
        int rows = sheet.getRows();
        if (rows > maxrows) {
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("文件内容错误");
            resultInfo.setResult("目前支持最大的导入数量为每次" + maxrows + "条，烦请分多次导入");
            return resultInfo;
        }
        // 判断是否使用了提供的模板
        Range[] range = sheet.getMergedCells();
        if (range.length != 1) {
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("模板使用错误");
            resultInfo.setResult("模板错误，请使用系统提供模板，请勿随意修改模板格式。");
            return resultInfo;
        }
        if (StringUtils.isEmpty(range[0].getTopLeft().getContents())) {
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("模板使用错误");
            resultInfo.setResult("模板错误，请使用系统提供模板，请勿随意修改模板格式。");
            return resultInfo;
        }
        Cell orgNameColCell = sheet.getCell(0, 1);//部门名称
        Cell orgStatusColCell = sheet.getCell(1, 1);//部门状态
        Cell isSecretColCell = sheet.getCell(2, 1);//是否涉密
        Cell isCompColCell = sheet.getCell(3, 1);//是否主管
        Cell compNameColCell = sheet.getCell(4, 1);//主管部门
        Cell ownSysColCell = sheet.getCell(5, 1);//党委，政府……
        Cell orgTypeColCell = sheet.getCell(6, 1);//行政机关，事业单位
        if (!("部门名称".equals(orgNameColCell.getContents().trim())
                && "部门状态".equals(orgStatusColCell.getContents().trim())
                && "是否涉密".equals(isSecretColCell.getContents().trim())
                && "是否主管部门".equals(isCompColCell.getContents().trim())
                && "主管部门".equals(compNameColCell.getContents().trim())
                && "所属系统".equals(ownSysColCell.getContents().trim())
                && "机构类型".equals(orgTypeColCell.getContents().trim())))
        {
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("模板使用错误");
            resultInfo.setResult("导入部门库信息的文件模板使用不正确，烦请使用提供的导入模板");
            return resultInfo;
        }
        // 查询地区下所有部门库信息
        OrganizationVo orgvo = new OrganizationVo();
        orgvo.setAreaId(areaid);
        JSONObject orgJson = service.findOrgByParam(orgvo);
        List<OrganizationEntity> orgList =
                FastJsonUtil.getList(orgJson.getJSONArray("result").toJSONString(), OrganizationEntity.class);
        Map<String, String> orgListMap = new HashMap<String, String>();
        for (OrganizationEntity temp : orgList) {
            orgListMap.put(temp.getName(), temp.getId());
        }
        // 查询地区下所有用户信息
        RcUserVo ruvo = new RcUserVo();
        ruvo.setAreaId(areaid);
        JSONObject userJson = userService.findListByCondtion(ruvo);
        List<RcUserEntity> rcUserList =
                FastJsonUtil.getList(userJson.getJSONArray("result").toJSONString(), RcUserEntity.class);
        Map<String, String> rcUserListMap = new HashMap<String, String>();
        for (RcUserEntity temp : rcUserList) {
            rcUserListMap.put(temp.getLoginName(), String.valueOf(temp.getId()));
        }
        // 查询所属系统字典
        JSONObject ownsysJson = dicService.getDicByKey("ownsys");
        List<Dictionary> ownsysList =
                FastJsonUtil.getList(ownsysJson.getJSONArray("result").toJSONString(), Dictionary.class);
        Map<String, String> ownsysMap = new HashMap<String, String>();
        Map<String, String> ownsysImMap = new HashMap<String, String>();
        for (Dictionary temp : ownsysList) {
            ownsysMap.put(temp.getName(), temp.getValue());
        }
        // 查询机构类型字典
        JSONObject deptFuncTypesJson = dicService.getDicByKey("orgType");
        List<Dictionary> deptFuncTypesList =
                FastJsonUtil.getList(deptFuncTypesJson.getJSONArray("result").toJSONString(), Dictionary.class);
        Map<String, String> deptFuncTypesMap = new HashMap<String, String>();
        for (Dictionary temp : deptFuncTypesList) {
            deptFuncTypesMap.put(temp.getName(), temp.getValue());
        }

        //查询地区code
        JSONObject areaJson = areaService.getAreaInfo(areaid);
        AreaVo area = FastJsonUtil.getObject(areaJson.getJSONObject("result").toJSONString(), AreaVo.class);

        UserInfoVo userInfoVo = null;
        UserExtEntity userExtEntity = null;
        UserEntity userEntity = null;
        UserAreaEntity userAreaEntity = null;
        OuserEntity ouserEntity = null;
        JSONObject retUserInfoJson = null;
        Map<String, List<String>> errorMap = new HashMap<String, List<String>>();
        List<String> errorList = new ArrayList<String>();
        errorMap.put("error", errorList);
        // 遍历导入文件的内容
        for (int i = 0; i < rows - 2; i++) {
            Cell orgNameCell = sheet.getCell(0, i + 2);//部门名称
            Cell orgStatusCell = sheet.getCell(1, i + 2);//部门状态
            Cell isSecretCell = sheet.getCell(2, i + 2);//是否涉密
            Cell isCompCell = sheet.getCell(3, i + 2);//是否主管
            Cell compNameCell = sheet.getCell(4, i + 2);//主管部门
            Cell ownSysCell = sheet.getCell(5, i + 2);//党委，政府……
            Cell orgTypeCell = sheet.getCell(6, i + 2);//行政机关，事业单位
            if (StringUtils.isEmpty(orgNameCell.getContents())
                    && StringUtils.isEmpty(orgStatusCell.getContents())
                    && StringUtils.isEmpty(isSecretCell.getContents())
                    && StringUtils.isEmpty(isCompCell.getContents())
                    && StringUtils.isEmpty(compNameCell.getContents())
                    && StringUtils.isEmpty(ownSysCell.getContents())
                    && StringUtils.isEmpty(orgTypeCell.getContents()))
            {
                //空行
                continue;
            }
            String orgName = orgNameCell.getContents().trim();
            if(StringUtils.isNotBlank(ownsysImMap.get(orgName))){
                errorMap.get("error").add("第" + (i + 3) + "行的[部门名称]在文档中重复");
            }
            ownsysImMap.put(orgName, "1");
        }
        for (int i = 0; i < rows - 2; i++) {

            // 取得编制域名的姓名
//			Cell fullNameCell = sheet.getCell(0, i+2);
//			Cell deptNameCell = sheet.getCell(1, i+2);

            Cell orgNameCell = sheet.getCell(0, i + 2);//部门名称
            Cell orgStatusCell = sheet.getCell(1, i + 2);//部门状态
            Cell isSecretCell = sheet.getCell(2, i + 2);//是否涉密
            Cell isCompCell = sheet.getCell(3, i + 2);//是否主管
            Cell compNameCell = sheet.getCell(4, i + 2);//主管部门
            Cell ownSysCell = sheet.getCell(5, i + 2);//党委，政府……
            Cell orgTypeCell = sheet.getCell(6, i + 2);//行政机关，事业单位

            if (StringUtils.isEmpty(orgNameCell.getContents())
                    && StringUtils.isEmpty(orgStatusCell.getContents())
                    && StringUtils.isEmpty(isSecretCell.getContents())
                    && StringUtils.isEmpty(isCompCell.getContents())
                    && StringUtils.isEmpty(compNameCell.getContents())
                    && StringUtils.isEmpty(ownSysCell.getContents())
                    && StringUtils.isEmpty(orgTypeCell.getContents()))
            {
                //空行
                continue;
            }
            String orgName = orgNameCell.getContents().trim();
            String orgStatus = orgStatusCell.getContents().trim();
            String isSecretCn = isSecretCell.getContents().trim();
            String isCompCN = isCompCell.getContents().trim();
            String isSecret = "0";
            if("是".equals(isSecretCn)){
                isSecret = "1";
            }else if("否".equals(isSecretCn)){
                isSecret = "0";
            }else{
                isSecret = "";
            }
            String isComp = "0";
            if("是".equals(isCompCN)){
                isComp = "1";
            }else if("否".equals(isCompCN)){
                isComp = "0";
            }else{
                isComp = "";
            }
            String compName = compNameCell.getContents().trim();
            String ownSys = ownSysCell.getContents().trim();
            String orgType = orgTypeCell.getContents().trim();
//			if(StringUtils.isEmpty(fullNameCell.getContents()) &&
//					StringUtils.isEmpty(deptNameCell.getContents())) {
//				continue;
//			}
            if (StringUtils.isBlank(orgName)) {
                errorMap.get("error").add("第" + (i + 3) + "行的[部门名称]为空");
            }
            if (StringUtils.isNotBlank(orgListMap.get(orgName))) {
                errorMap.get("error").add("第" + (i + 3) + "行的[部门名称]在数据库中已经存在");
            }
            if (orgName.length() > 35) {
                errorMap.get("error").add("第" + (i + 3) + "行的[部门名称]长度不能大于35字符");
            }
            if (StringUtils.isBlank(orgStatus)) {
                errorMap.get("error").add("第" + (i + 3) + "行的[部门状态]为空");
            } else {
                if (!"正常".equals(orgStatus) && !"已撤销".equals(orgStatus)) {
                    errorMap.get("error").add("第" + (i + 3) + "行的[部门状态]填写错误");
                }
            }
            if (StringUtils.isBlank(isSecretCn)) {
                errorMap.get("error").add("第" + (i + 3) + "行的[是否涉密]为空");
            } else {
                if (!"1".equals(isSecret) && !"0".equals(isSecret)) {
                    errorMap.get("error").add("第" + (i + 3) + "行的[是否涉密]填写错误");
                }
            }
            if (StringUtils.isBlank(isCompCN)) {
                errorMap.get("error").add("第" + (i + 3) + "行的[是否主管部门]为空");
            } else {
                if (!"1".equals(isComp) && !"0".equals(isComp)) {
                    errorMap.get("error").add("第" + (i + 3) + "行的[是否主管部门]填写错误");
                }
                if ("0".equals(isComp) && StringUtils.isBlank(compName)) {
                    errorMap.get("error").add("第" + (i + 3) + "行的[主管部门]为空");
                }
            }
            if (StringUtils.isBlank(ownSys)) {
                errorMap.get("error").add("第" + (i + 3) + "行的[所属系统]为空");
            }
            if (StringUtils.isBlank(orgType)) {
                errorMap.get("error").add("第" + (i + 3) + "行的[机构类型]为空");
            }else{
                if (StringUtils.isBlank(deptFuncTypesMap.get(orgType))) {
                    errorMap.get("error").add("第" + (i + 3) + "行的[机构类型]填写错误");
                }
            }

            // 验证所属系统是否存在【所属系统】db字典中
            if (StringUtils.isBlank(ownsysMap.get(ownSys))) {
                errorMap.get("error").add("第" + (i + 3) + "行的[所属系统]填写错误");
            }

            Date now = new Date();
            OrganizationEntity orgEntity = new OrganizationEntity();
//			orgEntity.setId();
            orgEntity.setParentId("");
            orgEntity.setName(orgName);
            orgEntity.setType(deptFuncTypesMap.get(orgType));
            orgEntity.setOwnSys(ownsysMap.get(ownSys));
            orgEntity.setStatus("正常".equals(orgStatus)?"0":"2");
            orgEntity.setSort(orgEntity.getId());
            orgEntity.setAreaId(areaid);
            orgEntity.setAreaCode(area.getCode());
            orgEntity.setIsComp(isComp);
            if ("0".equals(isComp)) {
                //非主管部门，设置parent_id
                if (StringUtils.isBlank(orgListMap.get(compName)) && StringUtils.isBlank(ownsysImMap.get(compName))) {
                    errorMap.get("error").add("第" + (i + 3) + "行的[主管部门]未找到，请先维护主管部门部门库信息。");
                } else if (StringUtils.isNotBlank(orgListMap.get(compName))) {
                    orgEntity.setParentId(orgListMap.get(compName));
                } else {
                    orgEntity.setParentId("0");//主管部门
                    orgEntity.setRemarks(compName);
                }
            }
            //判断主管部门是否是自己
            if(StringUtils.isNotBlank(orgName) && orgName.equals(compName)){
                errorMap.get("error").add("第" + (i + 3) + "行的[单位名称]与[主管部门]不能相同。");
            }
            orgEntity.setIsSecret(isSecret);
            orgEntity.setCreateTime(now);
            orgEntity.setUpdateTime(now);
            // 部门库创建用户ID
            if (StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
                orgEntity.setUpdateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
                orgEntity.setCreateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
            }
            // 部门库创建时间
            orgEntity.setCreateTime(new Date());
            orgEntityList.add(orgEntity);
            userInfoVo = new UserInfoVo();

            // **************用户扩展信息实体**************
            userExtEntity = new UserExtEntity();
            userExtEntity.setUserType(UserExtEntity.USER_TYPE_WBJ);
            // **************用户基本信息实体**************
            userEntity = new UserEntity();
            userEntity.setUsername(orgName);
            if (StringUtils.isNotBlank(rcUserListMap.get(orgName))) {
                userExtEntity.setUserId(Integer.valueOf(rcUserListMap.get(orgName)));
                //用户已经存在，不做修改，继续执行
                //查询用户信息
                // 设置用户类别
                userInfoVo.setUserExtEntity(userExtEntity);
                userEntity.setUserId(Integer.valueOf(rcUserListMap.get(orgName)));
                continue;
            }

            // 设置用户类别
            userInfoVo.setUserExtEntity(userExtEntity);

            // 取得编制域名的所属科室
//			if(StringUtils.isEmpty(deptNameCell.getContents())) {
//				errorMap.get("error").add("第" + (i+3) + "行的[所属科室]为空" );
//			}
//			if(StringUtils.isNotBlank(deptNameCell.getContents())) {
//				// 判断所输入的所属科室是否超过了指定的长度
//				if(deptNameCell.getContents().length() > deptNameMaxLen) {
//					errorMap.get("error").add("第" + (i+3) + "行的[所属科室]最大允许输入的长度为"+ deptNameMaxLen );
//				}
//			}
//			userEntity.setDeptName(deptNameCell.getContents());
            userEntity.setGroupId(1);
            userEntity.setEmail("batchimport@email.com");
            userEntity.setRegisterTime(new Date());
            // 设置注册用户ID
            userEntity.setRegisterUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
            // 设置注册用户IP
            userEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
            userEntity.setLastLoginTime(new Date());
            userEntity.setLastLoginIp(initLastLoginIp);
            userEntity.setLoginCount(0);
            //编制域名
            userEntity.setIsOrgDomain(UserEntity.ORG_DOMAIN_NAME_FLAG);
            userEntity.setIsAdmin(1);
            userEntity.setIsDeleted(0);
            userEntity.setIsViewonlyAdmin(0);
            userEntity.setIsSelfAdmin(0);
            userEntity.setFileTotal(0);
            userEntity.setGrain(0);
            userEntity.setRank(0);
            userEntity.setUploadSize(0);
            userEntity.setUploadTotal(0);
            userEntity.setIsDisabled(0);

            List<RoleEntity> roleList = new ArrayList<RoleEntity>();
            RoleEntity roleEntity = new RoleEntity();
            // 设置导入用户的默认角色
            roleEntity.setRoleId(Integer.valueOf(RoleEntity.ROLE_WBJ));
            roleList.add(roleEntity);
            userEntity.setRoleList(roleList);

            userInfoVo.setUserEntity(userEntity);

            // **************用户区域信息实体**************
            userAreaEntity = new UserAreaEntity();
            userAreaEntity.setAreaId(areaid);
            userAreaEntity.setAreaCode(area.getCode());
            userInfoVo.setUserAreaEntity(userAreaEntity);

            // **************用户私密信息实体**************
            ouserEntity = new OuserEntity();
            // 设置加密密码 初始密码定义常量
            ouserEntity.setPassword(DigestUtils.md5Hex("123456qwe"));
            // 设置注册时间
            ouserEntity.setRegisterTime(new Date());
            // 设置注册用户IP
            ouserEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
            ouserEntity.setLastLoginTime(new Date());
            ouserEntity.setLastLoginIp(initLastLoginIp);
            ouserEntity.setLoginCount(0);
            ouserEntity.setErrorCount(0);
            ouserEntity.setActivation(1);
            userInfoVo.setOuserEntity(ouserEntity);

            userInfoVoList.add(userInfoVo);
        }
        if (errorMap.get("error").size() > 0) {
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("文件内容错误");
            resultInfo.setResult(errorMap);
            return resultInfo;
        }
        // 用户导入的数据为空场合
//        if (userInfoVoList.size() == 0) {
//            resultInfo.setCode(ResultPojo.CODE_FAILURE);
//            resultInfo.setMsg("文件内容错误");
//            resultInfo.setResult("导入文件中的姓名和所属科室为空");
//            return resultInfo;
//        }
        //批量添加部门
        JSONObject dbOrgInfoJson = null;
        if(orgEntityList.size()>500){
            List<List<OrganizationEntity>> lists = Collections3.averageAssign(orgEntityList,5);
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(0));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(1));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(2));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(3));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(4));
        }else if(orgEntityList.size() > 0){
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(orgEntityList);
        }
        //JSONObject dbOrgInfoJson = service.saveOrUpdateOrgInfoList(orgEntityList);
        if (!ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code"))) {
            // 保存失败场合
            resultInfo.setCode(dbOrgInfoJson.getString("code"));
            resultInfo.setMsg("[service.saveOrUpdateOrgInfoList] in function of cudImportOrganizationByExcel "
                    + ResultPojo.MSG_FAILURE + "【" + dbOrgInfoJson.getString("msg") + "】");
            resultInfo.setResult(dbOrgInfoJson.getJSONArray("result"));
            return resultInfo;
        }
        List<OrganizationEntity> dbOrgInfoList =
                FastJsonUtil.getList(dbOrgInfoJson.getJSONObject("result").getJSONArray("retInfo").toJSONString(),
                        OrganizationEntity.class);

        // 查询地区下所有部门库信息
        orgJson = service.findOrgByParam(orgvo);
        orgList =
                FastJsonUtil.getList(orgJson.getJSONArray("result").toJSONString(), OrganizationEntity.class);
        orgListMap = new HashMap<String, String>();
        for (OrganizationEntity temp : orgList) {
            orgListMap.put(temp.getName(), temp.getId());
        }

        //循环orgEntityList
        List<OrganizationEntity> updateOrgList = new ArrayList<OrganizationEntity>();
        for (OrganizationEntity temp : dbOrgInfoList) {
            if("0".equals(temp.getParentId())){
                temp.setParentId(orgListMap.get(temp.getRemarks()));
                updateOrgList.add(temp);
            }
        }
        //批量添加部门 第二次主要为了更新parentid
        if(updateOrgList.size()>500){
            List<List<OrganizationEntity>> lists = Collections3.averageAssign(updateOrgList,5);
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(0));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(1));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(2));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(3));
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(lists.get(4));
        }else if(updateOrgList.size()>0){
            dbOrgInfoJson = service.saveOrUpdateOrgInfoList(updateOrgList);
        }
        //dbOrgInfoJson = service.saveOrUpdateOrgInfoList(updateOrgList);
        if (!ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code"))) {
            // 保存失败场合
            resultInfo.setCode(dbOrgInfoJson.getString("code"));
            resultInfo.setMsg("[service.saveOrUpdateOrgInfoList] in function of cudImportOrganizationByExcel "
                    + ResultPojo.MSG_FAILURE + "【" + dbOrgInfoJson.getString("msg") + "】");
            resultInfo.setResult(dbOrgInfoJson.getJSONArray("result"));
            return resultInfo;
        }

        // 用户部门库绑定
        List<UserInfoVo> userSaveInfoVoList = new ArrayList<UserInfoVo>();
        for (UserInfoVo info : userInfoVoList) {
            String orgName = info.getUserEntity().getUsername();
            //org Map 中匹配用户的username  然后设置orgid;
            info.getUserExtEntity().setOrgId(Integer.valueOf(orgListMap.get(orgName)));
        }
        if(userInfoVoList.size()>500){
            List<List<UserInfoVo>> lists = Collections3.averageAssign(userInfoVoList,5);
            retUserInfoJson = userService.saveOrUpdateUserInfoList(lists.get(0));
            retUserInfoJson = userService.saveOrUpdateUserInfoList(lists.get(1));
            retUserInfoJson = userService.saveOrUpdateUserInfoList(lists.get(2));
            retUserInfoJson = userService.saveOrUpdateUserInfoList(lists.get(3));
            retUserInfoJson = userService.saveOrUpdateUserInfoList(lists.get(4));
        }else if(userInfoVoList.size()>0){
            retUserInfoJson = userService.saveOrUpdateUserInfoList(userInfoVoList);
        }
        // 判断保存是否成功失败
        if (retUserInfoJson!= null && !ResultPojo.CODE_SUCCESS.equals(retUserInfoJson.getString("code"))) {
            // 保存失败场合
            resultInfo.setCode(retUserInfoJson.getString("code"));
            resultInfo.setMsg("[userService.saveOrUpdate] in function of cudImportOrganizationByExcel "
                    + ResultPojo.MSG_FAILURE + "【" + retUserInfoJson.getString("msg") + "】");
            resultInfo.setResult(null);
            return resultInfo;
        }

        // 成功保存部门信息表和部门状态表返回
        return retUserInfoJson;
    }

    /**
     * 上传文件的检验
     *
     * @param file 校验文件
     * @param maxVolumePram 文件最大限制
     * @param nameMaxlengthPram 文件名称最大长度
     * @param allowSuffixPram 文件后缀
     * @return 返回文件check信息
     */
    public String checkFileProperties(MultipartFile file, int maxVolumePram, int nameMaxlengthPram,
            String allowSuffixPram)
    {
        // 文件最大限制
        if (maxVolumePram == 0) {
            maxVolumePram = this.maxVolume;
        }

        // 文件名称最大长度
        if (nameMaxlengthPram == 0) {
            nameMaxlengthPram = this.nameMaxlength;
        }

/*		// 文件后缀
        if(StringUtils.isEmpty(allowSuffixPram)){
			allowSuffixPram = this.allowSuffix;
		}*/

        // 文件为空Check
        if (null == file) {
            return "上传文件为空！";
        }

        String origName = file.getOriginalFilename();
        //String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);

        // 上传非法文件Check
        if (origName.contains("../") || origName.contains("..\\")) {
            return "上传的文件" + origName + "非法";
        }

/*		// 非允许的后缀Check
        if(!this.isAllowSuffix(ext,allowSuffixPram)){
			return ext + "格式的文件不允许上传";
		}*/

        // 超过附件大小限制
        if (!this.isAllowMaxFile((int) (file.getSize() / 1024), maxVolumePram)) {
            return "您上传的文件" + origName + ",大于单文件大小限制" + maxVolumePram + "KB";
        }

        // 文件名长度限制
        if (origName.lastIndexOf('.') > nameMaxlengthPram) {
            return "您上传的文件名不能超过" + nameMaxlengthPram + "个字";
        }

        return StringUtils.EMPTY;
    }

    /**
     * 检查文件后缀是否符合标准
     *
     * @param ext 上传文件后缀
     * @param allowSuffixStr 文件后缀允许范围
     * @return 返回后缀判断结果
     */
    /*private boolean isAllowSuffix(String ext, String allowSuffixStr){
        // 文件后缀为空
		if(StringUtils.isBlank(ext)){
			return false;
		}
		// 后缀范围为空(没有后缀限制)
		if(StringUtils.isBlank(allowSuffixStr)){
			return true;
		}

		String[] as = allowSuffixStr.split(",");
		for(int i=0;i<as.length;i++){
			if(ext.equals(as[i])){
				return true;
			}
		}
		return false;
	}*/

    /**
     * 是否允许上传，根据文件大小
     *
     * @param size 文件大小，单位KB
     * @param maxVolumeInt 文件允许大小，单位KB
     * @return 判断文件是否符合大小限制
     */
    private boolean isAllowMaxFile(int size, int maxVolumeInt)
    {
        // 限制大小为0时，不做文件大小限制
        if (maxVolumeInt == 0) {
            return true;
        }

        // 超出文件大小限制
        return maxVolumeInt >= size;
    }
}
